# @Time : 2021/5/14 11:42
# @Author : Fioman 
# @Phone : 13149920693
from settings import *
from tools.hd_logger import HdLogger
from tools.common_tools import get_time_now_string
import cv2 as cv
import numpy as np
import json
from PIL.Image import Image

"""
将图片保存进电脑设备中的模块,这个模块主要用来保存设备中的图片.包括标定的时候,或者是其他的时候的图片一并保存进来.
"""
logger = HdLogger()

def get_size_scale_image(imageSrc, sizeScale):
    """
    高宽同等比例缩放图像,缩放比例
    :param imageSrc: 原图像
    :param sizeScale: 缩放比例
    :return:
    """
    h, w = imageSrc.shape[:2]
    newWidth, newHeight = int(w / sizeScale), int(h / sizeScale)
    newImage = cv.resize(imageSrc, (newWidth, newHeight), cv.INTER_AREA)
    return newImage


def delete_exist_index_image(keepDir, boardIndex):
    """
    遍历保存图像的目录,删除将要保存的相同id的图片
    :param keepDir:图片保存目录
    :param boardIndex:图像id序列号
    :return:
    """
    for root, dirs, files in os.walk(keepDir):
        for file in files:
            try:
                index = file.split('--')[0]
                if index == str(boardIndex):
                    os.remove(os.path.join(root, file))
            except Exception as e:
                print(str(e))
                
def delete_overflow_image(path, maxNum):
    """
    遍历识别失败图片保存目录，防止图片保存太多导致爆盘
    """
    count = 0
    try:
        for root, dirs, files in os.walk(path):
            for each in files:
                count += 1
        if count > maxNum:
            del_list = os.listdir(path)
            if not del_list:
                dir_path = del_list
            else:
                """
                注意，这里使用的是 lambda 表达式，将文件按照升序排列
                os.path.getmtime() 函数是获取文件最后的修改时间
                os.path.getctime() 函数是获取文件最后创建的时间
                """
                dir_path = sorted(del_list, key=lambda x: os.path.getmtime(os.path.join(path, x)))
            file_path = os.path.join(path, dir_path[0])
            if os.path.isfile(file_path):
                os.remove(file_path)
    except Exception as e:
        print(e)

def save_ok_image(keepIndex,keepImage,width,height):
    """
    保存识别成功的图片
    :param keepIndex:
    :param keepImage:
    :param width:
    :param height:
    :return:
    """
    try:
        keepDir = RAW_OK_DIR
        delete_exist_index_image(keepDir,keepIndex)
        fileName = "{}--{}--w_{}--h_{}.bmp".format(keepIndex,get_time_now_string(),width,height)
        cv.imwrite(os.path.join(keepDir,fileName),keepImage) # 保存原图
    except Exception as e:
        errorInfo = "in save_ok_image() error: {}".format(str(e))
        print(errorInfo)
        logger.debug(errorInfo)

def save_fail_image(keepIndex,keepImage,width,height):
    """
    保存识别失败的图片
    :param keepIndex:
    :param keepImage:
    :param width:
    :param height:
    :return:
    """
    try:
        keepDir = RAW_FAIL_DIR
        delete_exist_index_image(keepDir,keepIndex)
        fileName = "{}--{}--w_{}--h_{}.bmp".format(keepIndex,get_time_now_string(),width,height)
        cv.imwrite(os.path.join(keepDir,fileName),keepImage) # 保存原图
    except Exception as e:
        errorInfo = "in save_fail_image() error: {}".format(str(e))
        print(errorInfo)
        logger.debug(errorInfo)

def save_fail_res_image(keepIndex,keepImage,width,height):
    """
    保存识别失败的图片
    :param keepIndex:
    :param keepImage:
    :param width:
    :param height:
    :return:
    """
    try:
        keepDir = RAW_FAIL_RES_DIR
        delete_exist_index_image(keepDir,keepIndex)
        fileName = "{}--{}--w_{}--h_{}.bmp".format(keepIndex,get_time_now_string(),width,height)
        cv.imwrite(os.path.join(keepDir, fileName),keepImage)
    except Exception as e:
        errorInfo = "in save_fail_image() error: {}".format(str(e))
        print(errorInfo)
        logger.debug(errorInfo)

def save_ok_image_color(keepIndex,keepImage,dirFlag,imageResized):
    """
    保存识别成功的图片
    :param keepIndex:
    :param keepImage:
    :param width:
    :param height:
    :return:
    """
    try:
        keepIndexColor = int(keepIndex / 1)
        if dirFlag == "ok":
            keepDir = RAW_OK_DIR_OCR_SMALL
        else:
            keepDir = RAW_FAIL_DIR_OCR_SMALL
        delete_exist_index_image(keepDir, keepIndexColor)
        fileName = "{}--{}.bmp".format(keepIndexColor, get_time_now_string())
        cv.imwrite(os.path.join(keepDir,fileName),imageResized) # 保存缩放后的图片
            # 保存原图
        keepDir = RAW_OCR_ORIGINAL
        delete_exist_index_image(keepDir,keepIndexColor)
        fileName = "{}--{}.bmp".format(keepIndexColor, get_time_now_string())
        cv.imwrite(os.path.join(keepDir,fileName),keepImage)

    except Exception as e:
        errorInfo = "in save_ok_image() error: {}".format(str(e))
        print(errorInfo)
        logger.debug(errorInfo)

def save_fail_image_color(keepIndex, keepImage, width, height, maxNum):
    """
    保存识别失败的图片
    :param keepIndex:
    :param keepImage:
    :param width:
    :param height:
    :return:
    """
    try:
        keepDir = RAW_FAIL_DIR_OCR_SMALL
        delete_exist_index_image(keepDir, keepIndex)
        delete_overflow_image(keepDir, maxNum)
        fileName = "{}--{}--w_{}--h_{}.bmp".format(keepIndex, get_time_now_string(), width, height)
        cv.imwrite(os.path.join(keepDir,fileName), keepImage) # 保存原图
    except Exception as e:
        errorInfo = "in save_fail_image() error: {}".format(str(e))
        print(errorInfo)
        logger.debug(errorInfo)

def save_fail_res_image_color(keepIndex,keepImage,width,height,maxNum):
    """
    保存识别失败的图片
    :param keepIndex:
    :param keepImage:
    :param width:
    :param height:
    :return:
    """
    try:
        keepDir = RAW_FAIL_RES_DIR_COLOR
        delete_exist_index_image(keepDir,keepIndex)
        delete_overflow_image(keepDir, maxNum)
        fileName = "{}--{}--w_{}--h_{}.bmp".format(keepIndex,get_time_now_string(),width,height)
        cv.imwrite(os.path.join(keepDir, fileName), get_size_scale_image(keepImage,3))
    except Exception as e:
        errorInfo = "in save_fail_image() error: {}".format(str(e))
        print(errorInfo)
        logger.debug(errorInfo)

def save_ok_res_image(keepIndex,keepImage):
    """
    保存识别的结果的图片
    :param keepIndex:
    :param keepImage:
    :return:
    """
    try:
        keepDir = RAW_RES_DIR  # 首板尺寸确认保存的图片
        delete_exist_index_image(keepDir, keepIndex)
        fileName = "{}--{}.bmp".format(keepIndex, get_time_now_string())
        cv.imwrite(os.path.join(keepDir, fileName), get_size_scale_image(keepImage,3))
    except Exception as e:
        errorInfo = "in save_ok_res_image() error:{}".format(str(e))
        print(errorInfo)
        logger.debug(errorInfo)

def save_demarcate_image(keepImage):
    """
    保存识别的结果的图片
    :param keepIndex:
    :param keepImage:
    :return:
    """
    try:
        keepIndex = 111
        keepDir = RAW_DEMARCATE_DIR  # 首板尺寸确认保存的图片
        delete_exist_index_image(keepDir, keepIndex)
        fileName = "{}--{}.bmp".format(keepIndex, get_time_now_string())
        image = get_size_scale_image(keepImage,1)
        cv.imwrite(os.path.join(keepDir, fileName), image)
    except Exception as e:
        errorInfo = "in save_ok_res_image() error:{}".format(str(e))
        print(errorInfo)
        logger.debug(errorInfo)


def save_demarcate_color_image(keepImage):
  """
  保存识别的结果的图片
  :param keepIndex:
  :param keepImage:
  :return:
  """
  try:
    keepIndex = 111
    keepDir = RAW_COLOR_DEMARCATE_DIR  # 首板尺寸确认保存的图片
    delete_exist_index_image(keepDir, keepIndex)
    fileName = "{}--{}.bmp".format(keepIndex, get_time_now_string())
    image = get_size_scale_image(keepImage, 1)
    cv.imwrite(os.path.join(keepDir, fileName), image)
  except Exception as e:
    errorInfo = "in save_ok_res_image() error:{}".format(str(e))
    print(errorInfo)
    logger.debug(errorInfo)



def open_database_dump_dir():
    """
    打开数据库备份的目录
    :return:
    """
    openDir = DATA_BASE_DUMP_DIR
    ret = os.system("explorer.exe {}".format(openDir))
    return "ok" if ret == 1 else ret


def open_database_import_dir():
    """
    打开数据库导入的目录
    :return:
    """
    openDir = DATA_BASE_IMPORT_DIR
    ret = os.system("explorer.exe {}".format(openDir))
    return "ok" if ret == 1 else ret

if __name__ == '__main__':
    path = "E:\jianye_plate"
    del_list = os.listdir(path)
    print("del_list", del_list)
    if not del_list:
        dir_path = del_list
    else:
        """
        注意，这里使用的是 lambda 表达式，将文件按照升序排列
        os.path.getmtime() 函数是获取文件最后的修改时间
        os.path.getctime() 函数是获取文件最后创建的时间
        """
        dir_path = sorted(del_list, key=lambda x: os.path.getmtime(os.path.join(path, x)))
    print("dir_path", dir_path)
    print(dir_path[0])
    # os.remove(os.path.join(path, dir_path[0]))
